#    Copyright (C) 2019 Mason Hock <mason@masonhock.com>
#
#    This program is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program; if not, write to the Free Software
#    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
#

import requests

import musicbrainzngs

musicbrainzngs.set_useragent("Libricia", "0.x")

JAMENDO_BASE_URL = "https://api.jamendo.com/v3.0/tracks/?"

JAMENDO_OPTIONS = [
    ("client_id", "8e4fe531"),
    ("format", "jsonpretty"),
    ("ccnc", "0"),
    ("ccnd", "0"),
]


class Search:
    def __init__(self):
        self.results = []

    def search_artists(self, query):
        if len(query) > 2:
            self.results = [
                result
                for result in musicbrainzngs.search_artists(
                    artist=query, type="group", limit=4
                )["artist-list"]
            ]
        else:
            self.results = []


class Channelp:
    def __init__(self, artist):
        self.tags = artist.get_tags(0)
        self.pool = set()
        self.get_tracks_similar_to_artist(artist, 25)
        self.playlist = []

    def get_tracks_similar_to_artist(self, artist, num_results):
        by_xartist = JAMENDO_OPTIONS + [
            ("limit", str(num_results)),
            ("xartist", artist.data["name"]),
        ]

        by_tags = JAMENDO_OPTIONS + [
            ("limit", str(num_results)),
            ("fuzzytags", "+".join(artist.get_tags(0))),
        ]

        search_results = (
            requests.get(
                JAMENDO_BASE_URL + "&".join(["=".join(option) for option in by_xartist])
            ).json()["results"]
            + requests.get(
                JAMENDO_BASE_URL + "&".join(["=".join(option) for option in by_tags])
            ).json()["results"]
        )

        for result in search_results:
            self.pool.add(playback.Track.new_from_jamendo_data(result))

    def get_track(self):
        return random.sample(self.pool, 1)[0]
